package com.navinfo.parkingnavi;


import android.annotation.SuppressLint;
import android.graphics.PointF;
import android.graphics.RectF;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonElement;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import com.mapbox.api.directions.v5.models.RouteOptions;
import com.mapbox.geojson.Feature;
import com.mapbox.geojson.Point;
import com.mapbox.geojson.utils.PolylineUtils;
import com.mapbox.mapboxsdk.camera.CameraPosition;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource;
import com.mapbox.mapboxsdk.style.sources.Source;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncher;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncherOptions;
import com.navinfo.parkingnavi.Adapter.FloorListAdapter;
import com.navinfo.parkingnavi.fragment.PoiInfoFragment;
import com.navinfo.parkingnavi.fragment.PoiListFragment;
import com.navinfo.parkingnavi.fragment.RoutePanningFragment;
import com.navinfo.parkingnavi.fragment.SearchFragment;
import com.navinfo.parkingnavi.fragment.SelectMapPoiFragment;
import com.navinfo.parkingnavi.system.SystemConfig;
import com.navinfo.parkingnavi.system.UrlManager;
import com.navinfo.parkingnavi.util.GsonManager;
import com.navinfo.parkingnavi.util.LayerUtil;
import com.navinfo.parkingnavi.util.NetManager;
import com.navinfo.parkingnavi.util.StringUtils;
import com.navinfo.parkingnavi.util.SystemUtil;
import com.navinfo.parkingnavi.util.mode.ParkingFloor;
import com.navinfo.parkingnavi.util.mode.Poi;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.Group;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends MapActivity implements View.OnClickListener {
    /**
     * 搜索栏
     */
    private TextView mInputView;
    /**
     * 右下角四按钮
     */
    private View mZoomInBtn, mZoomOutBtn, mLocBtn, mNaviBtn, mSelectPoiIcon;
    /**
     * 取消按钮
     */
    private View mCancelBtn;

    private Group mMapBtnGroup;

    private Handler mHandler = new Handler(Looper.getMainLooper());

    private RecyclerView floorList;
    private FloorListAdapter floorListAdapter;
    private int mScreenWidth, mScreenHeight;
    private Call mFloorCall;
    //线路layerId
    private String routeLayerId = "mapbox-navigation-route-shield-layer";
    public static final String KEY_ROUTE_WHOLE = "KEY_ROUTE_WHOLE", KEY_ROUTE_OUT = "KEY_ROUTE_OUT", KEY_ROUTE_PARKING = "KEY_ROUTE_PARKING";

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mScreenWidth = SystemUtil.getScreenWidth(this);
        mScreenHeight = SystemUtil.getScreenHeight(this);
        mInputView = findViewById(R.id.main_input);
        mInputView.setOnClickListener(this);

        mZoomInBtn = findViewById(R.id.main_in);
        mZoomInBtn.setOnClickListener(this);

        mZoomOutBtn = findViewById(R.id.main_out);
        mZoomOutBtn.setOnClickListener(this);

        mLocBtn = findViewById(R.id.main_loc);
        mLocBtn.setOnClickListener(this);

        mCancelBtn = findViewById(R.id.main_cancel);
        mCancelBtn.setOnClickListener(this);

        mMapBtnGroup = findViewById(R.id.main_map_btn_group);

        mNaviBtn = findViewById(R.id.main_navi);
        mNaviBtn.setOnClickListener(this);

        mSelectPoiIcon = findViewById(R.id.main_select_map_poi_icon);

        floorList = findViewById(R.id.main_floors_list);
        floorListAdapter = new FloorListAdapter();
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        floorList.setLayoutManager(layoutManager);
        floorList.setAdapter(floorListAdapter);


        floorListAdapter.addOnItemClickListener(new FloorListAdapter.OnItemClickListener() {
            @Override
            public void onSelectFloor(String parkingId, final String floorId) {
                if (mFloorCall != null && mFloorCall.isExecuted()) {
                    mFloorCall.cancel();
                }
                mFloorCall = NetManager.getInstance().getData(UrlManager.getParkingVectorUrl(parkingId, floorId), new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("jingo", e.getMessage());
                        mFloorCall = null;
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        mFloorCall = null;
                        try {
                            JSONObject jsonObject = new JSONObject(response.body().string());
                            String road = jsonObject.getString("p_road");
                            String background = jsonObject.getString("p_background");
                            String poi = jsonObject.getString("p_poi");

                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    for (ParkingFloor floor : parkingFloorsList) {
                                        if (floor.getParkingId().equals(parkingId)) {
                                            floor.setSelectFloor(floorId);
                                        }
                                    }
                                    if (!TextUtils.isEmpty(background)) {
                                        Source geoJsonSource = mMapManager.getMapStyle().getSource(parkingId + "background");
                                        if (geoJsonSource != null)
                                            ((GeoJsonSource) geoJsonSource).setGeoJson(background);
                                    }
                                    if (!TextUtils.isEmpty(road)) {
                                        Source geoJsonSource = mMapManager.getMapStyle().getSource(parkingId + "road");
                                        if (geoJsonSource != null)
                                            ((GeoJsonSource) geoJsonSource).setGeoJson(road);
                                    }
                                    if (!TextUtils.isEmpty(poi)) {
                                        Source geoJsonSource = mMapManager.getMapStyle().getSource(parkingId + "poi");
                                        if (geoJsonSource != null) {
                                            ((GeoJsonSource) geoJsonSource).setGeoJson(poi);
                                        }
                                    }
                                    mMapManager.getNavigationMapboxMap().switchParkingFloor(parkingId, floorId);
                                }
                            });

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });


    }

    @Override
    protected void styleLoaded() {
        Uri uri = getIntent().getData();
        if (uri != null) {
            Poi poi = new Poi();
            String Name_zh = uri.getQueryParameter("Name_zh");
            poi.setName_zh(Name_zh);
            String Province_name = uri.getQueryParameter("Province_name");
            poi.setProvince_name(Province_name);
            String lon = uri.getQueryParameter("lon");
            poi.setLon(Double.parseDouble(lon));
            String lat = uri.getQueryParameter("lat");
            poi.setLat(Double.parseDouble(lat));
            String Kindcode = uri.getQueryParameter("Kindcode");
            poi.setKindcode(Kindcode);
            String Cityadcode = uri.getQueryParameter("Cityadcode");
            poi.setCityadcode(Cityadcode);
            String Admincode = uri.getQueryParameter("Admincode");
            poi.setAdmincode(Admincode);
            String City_name = uri.getQueryParameter("City_name");
            poi.setCity_name(City_name);
            String Admin_name = uri.getQueryParameter("Admin_name");
            poi.setAdmin_name(Admin_name);

            Bundle bundle = new Bundle();
            bundle.putSerializable(SystemConfig.Bundle_key_poi_feature, poi.toFeature());
            mFragmentsManager.showPoiInfoFragment(bundle, poiListener);
            mMapBtnGroup.setVisibility(View.GONE);

        }
    }


    private String loadJsonFromAsset(String filename) {
// Using this method to load in GeoJSON files from the assets folder.

        try {
            InputStream is = getAssets().open(filename);
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            return new String(buffer, Charset.forName("UTF-8"));

        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
    }

    //按钮点击
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_navi:
                showRoutePlanning(null);
                break;
            case R.id.main_input:
                //清除所有之前的marker
                mMapManager.clearAllLayer();
                Bundle bundle = new Bundle();
                //打开搜索页面
                if (mMapManager.getMapBox() != null) {
                    LatLng latLng = mMapManager.getMapBox().getCameraPosition().target;
                    bundle.putParcelable(SystemConfig.Bundle_key_latlng, latLng);
                }
                mFragmentsManager.showSearchFragment(bundle, searchListener);
                break;
            case R.id.main_in:
                //缩放地图
                if (mMapManager.getMapBox() != null)
                    mMapManager.getMapBox().animateCamera(CameraUpdateFactory.zoomIn());
                break;
            case R.id.main_out:
                //缩放地图
                if (mMapManager.getMapBox() != null) {
                    mMapManager.getMapBox().animateCamera(CameraUpdateFactory.zoomOut());
                }
                break;
            case R.id.main_loc:
                //回到我的位置
                Location location = mMapManager.getMapBox().getLocationComponent().getLastKnownLocation();
                if (location != null) {
                    mMapManager.jumpCurrentLoc();
                    if (!mFragmentsManager.bFragmentShow()) {
                        LoadLatlngInfo(new LatLng(location.getLatitude(), location.getLongitude()));
                    }
                }
                break;
            case R.id.main_cancel:
                //清空一切
                mInputView.setText("");
                mCancelBtn.setVisibility(View.GONE);
                mMapManager.clearAllLayer();
                mFragmentsManager.removeAllFragments();
                break;
        }
    }


    //地图点击
    @Override
    public boolean onMapClick(@NonNull LatLng point) {
        Feature feature = mMapManager.selectMapFeature(point);
        if (feature != null) {
            Bundle bundle = new Bundle();
            bundle.putSerializable(SystemConfig.Bundle_key_poi_feature, feature);
            mFragmentsManager.showPoiInfoFragment(bundle, poiListener);
            mMapBtnGroup.setVisibility(View.GONE);
            return true;
        }
        return super.onMapClick(point);
    }

    //poiList页面监听
    private PoiListFragment.OnPoiListFragmentListener poiListListener = new PoiListFragment.OnPoiListFragmentListener() {
        @Override
        public void onShowNearPoi(Poi centerPoi, Poi nearPoi) {
            if (nearPoi == null)
                return;
            Bundle bundle = new Bundle();
            bundle.putSerializable(SystemConfig.Bundle_key_poi_feature, nearPoi.toFeature());
            mFragmentsManager.showPoiInfoFragment(bundle, poiListener);
            mMapBtnGroup.setVisibility(View.GONE);
            mMapManager.showNearMarker(centerPoi, nearPoi);
        }

        @Override
        public void onShowRoutePlanning(Poi poi) {
            showRoutePlanning(poi);
        }

        @Override
        public void onDestroyView() {
            mMapBtnGroup.setVisibility(View.VISIBLE);
        }
    };

    //poi详情页面监听
    private PoiInfoFragment.OnPoiInfoFragmentListener poiListener = new PoiInfoFragment.OnPoiInfoFragmentListener() {

        @Override
        public void onClickClose() {
            mFragmentsManager.onBackPressed();
            mMapManager.clearCenterMarker();
            mMapManager.clearNearMarker();
        }

        @Override
        public void onClickSearch(Poi poi) {
            if (poi == null)
                return;
            Bundle bundle = new Bundle();
            bundle.putSerializable(SystemConfig.Bundle_key_poi, poi);
            mFragmentsManager.showSearchFragment(bundle, searchListener);

        }

        @Override
        public void onClickNavi(Poi poi) {
            showRoutePlanning(poi);
        }

        @Override
        public void onDestroyView() {
            mMapBtnGroup.setVisibility(View.VISIBLE);
        }
    };

    //poi搜索页面监听
    private SearchFragment.OnSearchFragmentListener searchListener = new SearchFragment.OnSearchFragmentListener() {
        @Override
        public void onDestroyView() {
            if (!curParkingId.equals("")) {
                floorList.setVisibility(View.VISIBLE);
            }
            mMapBtnGroup.setVisibility(View.VISIBLE);
        }

        @Override
        public void onSearchResult(String key, Poi centerPoi, String cityCode, ArrayList<Poi> list) {
            mFragmentsManager.onBackPressed();
            if (list != null) {
                mMapManager.showMarkers(list);
            }
            mInputView.setText(key);
            mCancelBtn.setVisibility(View.VISIBLE);
            Bundle bundle = new Bundle();
            bundle.putString(SystemConfig.Bundle_key_search_key, key);
            bundle.putSerializable(SystemConfig.Bundle_key_poi_list, list);
            bundle.putString(SystemConfig.Bundle_key_cityCode, cityCode);
            if (centerPoi != null) {
                mMapManager.showCenterMarker(centerPoi.toFeature());
            }
            mFragmentsManager.showPoiListFragment(bundle, poiListListener);
            mMapBtnGroup.setVisibility(View.GONE);
        }

        @Override
        public void onShowPoi(Poi poi) {
            if (poi != null) {
                mFragmentsManager.onBackPressed();
                Feature feature = poi.toFeature();
                mMapManager.showCenterMarker(feature);
                mMapManager.jumpPoi(poi);
                Bundle bundle = new Bundle();
                bundle.putSerializable(SystemConfig.Bundle_key_poi_feature, feature);
                mFragmentsManager.showPoiInfoFragment(bundle, poiListener);
                mMapBtnGroup.setVisibility(View.GONE);
            }
        }

        @Override
        public void onShowNearPoi(Poi centerPoi, Poi nearPoi) {
            if (centerPoi != null && nearPoi != null) {
                mFragmentsManager.onBackPressed();
                mMapManager.showNearMarker(centerPoi, nearPoi);
                Bundle bundle = new Bundle();
                bundle.putSerializable(SystemConfig.Bundle_key_poi_feature, nearPoi.toFeature());
                mFragmentsManager.showPoiInfoFragment(bundle, poiListener);
                mMapBtnGroup.setVisibility(View.GONE);
            }
        }

        @Override
        public void onShowRoute(Poi poi) {
            showRoutePlanning(poi);
        }
    };

    @Override
    public boolean onMapLongClick(@NonNull LatLng latLng) {
        if (mFragmentsManager.bFragmentShow())
            return false;
        LoadLatlngInfo(latLng);
        return true;
    }

    //楼层数据请求
    private Call mCall;
    private String flrId = null;
    private String parkingId = null;
    private String name = null;

    private void LoadLatlngInfo(LatLng latLng) {
        if (mCall != null && mCall.isExecuted())
            mCall.cancel();

        PointF pixel = mMapManager.getMapBox().getProjection().toScreenLocation(latLng);
        List<Feature> features = mMapManager.getMapBox().queryRenderedFeatures(pixel);
        flrId = null;
        parkingId = null;
        name = null;
        for (int i = 0; i < features.size(); i++) {
            if (parkingId != null && name != null && flrId != null) {
                break;
            }
            Feature feature = features.get(i);
            if (feature.properties() != null) {
                for (Map.Entry<String, JsonElement> entry : feature.properties().entrySet()) {
                    if (entry.getKey().equals("flr_id")) {
                        flrId = entry.getValue().toString();
                        if (flrId.startsWith("\"")) {
                            flrId = flrId.substring(1);
                        }
                        if (flrId.endsWith("\"")) {
                            flrId = flrId.substring(0, flrId.length() - 1);
                        }
                    }
                    if (entry.getKey().equals("parking_id")) {
                        parkingId = entry.getValue().toString();
                        if (parkingId.startsWith("\"")) {
                            parkingId = parkingId.substring(1);
                        }
                        if (parkingId.endsWith("\"")) {
                            parkingId = parkingId.substring(0, parkingId.length() - 1);
                        }
                    }
                    if (entry.getKey().equals("name")) {
                        name = entry.getValue().toString();
                        if (name.startsWith("\"")) {
                            name = name.substring(1);
                        }
                        if (name.endsWith("\"")) {
                            name = name.substring(0, name.length() - 1);
                        }
                    }
                    if (parkingId != null && name != null && flrId != null) {
                        break;
                    }
                }
            }
        }


        mCall = NetManager.getInstance().getData(UrlManager.getRGeoCodeUrl(latLng.getLatitude(), latLng.getLongitude()), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mCall = null;
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                mCall = null;
                Poi poi = GsonManager.getInstance().parseGeoCodePoi(response.body().string());
                if (poi != null) {
                    if (name != null && parkingId != null && flrId != null) {
                        poi.setName_zh(name);
                        poi.setFlrId(flrId);
                        poi.setParkingId(parkingId);
                    }
                    final Feature feature = poi.toFeature();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            mMapManager.showCenterMarker(feature);
                            Bundle bundle = new Bundle();
                            bundle.putSerializable(SystemConfig.Bundle_key_poi_feature, feature);
                            mFragmentsManager.showPoiInfoFragment(bundle, poiListener);
                            mMapBtnGroup.setVisibility(View.GONE);
                        }
                    });
                }
            }
        });
    }

    private void showRoutePlanning(Poi poi) {
        mFragmentsManager.onBackPressed();
        Bundle bundle = new Bundle();
        Poi locPoi = new Poi();
        Location location = mMapManager.getMapBox().getLocationComponent().getLastKnownLocation();
        if (location == null) {
            Toast.makeText(MainActivity.this, "没有获取到当前位置", Toast.LENGTH_SHORT).show();
            return;
        }
        locPoi.setName_zh("我的位置");
        locPoi.setLon(location.getLongitude());
        locPoi.setLat(location.getLatitude());
        if (poi != null) {
            bundle.putSerializable(SystemConfig.Bundle_key_poi, poi);
        }
        bundle.putSerializable(SystemConfig.Bundle_key_my_loc, locPoi);
        mFragmentsManager.showRoutePlanningFragment(bundle, routePanningFragmentListener);
        mMapManager.clearAllLayer();
        mMapBtnGroup.setVisibility(View.GONE);
    }

    private RoutePanningFragment.OnRoutePanningFragmentListener routePanningFragmentListener = new RoutePanningFragment.OnRoutePanningFragmentListener() {
        @Override
        public void onSelectPoiFromMap() {
            mInputView.setVisibility(View.GONE);
            mSelectPoiIcon.setVisibility(View.VISIBLE);
            mFragmentsManager.showSelectMapFragment(new SelectMapPoiFragment.OnSelectMapPoiFragmentListener() {
                @Override
                public void onSelectPoi(Poi poi) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(SystemConfig.Bundle_select_poi, poi);
                    mFragmentsManager.onBackPressed(bundle);
                }

                @Override
                public void onDestroyView() {
                    mSelectPoiIcon.setVisibility(View.GONE);
                    mInputView.setVisibility(View.VISIBLE);
                }
            });
        }

        @Override
        public void onShowRouteInfo(DirectionsRoute route, DirectionsRoute outRoute, List<DirectionsRoute> parkingRouteList) {
            if (parkingRouteList == null) {
                parkingRouteList = new ArrayList<>();
            }
            parkingRouteList.add(outRoute); // 默认将外部路径加到parkingRouteList的尾部，这样在渲染时会自动取出最后一个路径作为外部路径渲染，前面的路径作为停车场内路径渲染
            launchNavigationWithRoute(route, parkingRouteList);
            if (parkingRouteList!=null&&!parkingRouteList.isEmpty()){
                RouteOptions routeOptions=parkingRouteList.get(parkingRouteList.size()-1).routeOptions();
                if (StringUtils.isEmpty(routeOptions.accessToken())&&StringUtils.isEmpty(routeOptions.approaches())){
                    parkingRouteList.remove(parkingRouteList.size()-1);
                }
            }
//            Bundle bundle = new Bundle();
//            bundle.putSerializable(SystemConfig.Bundle_route_info, route);
//            mFragmentsManager.showRouteInfoFragment(bundle, null);
        }

        @Override
        public void onDestroyView() {
            mMapBtnGroup.setVisibility(View.VISIBLE);
        }
    };

    /**
     * //     * 启动导航界面
     * //
     */
    private void launchNavigationWithRoute(DirectionsRoute route, List<DirectionsRoute> parkingRoute) {
        if (route == null) {
            Toast.makeText(this, "路径不可用", Toast.LENGTH_SHORT).show();
            return;
        }

        NavigationLauncherOptions.Builder optionsBuilder = NavigationLauncherOptions.builder()
                .shouldSimulateRoute(true);
//        if (currentLocation == null) {
//            currentLocation = wayPoints.get(0); // 如果当前位置无法获取，则将wayPoints的第一个点作为起始点
//        }
        List<Point> routePointList=PolylineUtils.decode(route.geometry(), 6);
        CameraPosition initialPosition = new CameraPosition.Builder()
                .target(new LatLng(routePointList.get(0).latitude(), routePointList.get(0).longitude()))
                .tilt(0)
                .zoom(18)
                .build();
        optionsBuilder.initialMapCameraPosition(initialPosition);
        optionsBuilder.directionsRoute(route);
        optionsBuilder.parkingRouteList(parkingRoute);
        // TODO Testing dynamic offline
        NavigationLauncher.startNavigation(this, optionsBuilder.build());
    }

    @Override
    public void onCameraMove() {
        if (mMapManager.getMapBox().getCameraPosition().zoom >= 17) {
            mHandler.removeCallbacks(mapMoveRunnable);
            mHandler.postDelayed(mapMoveRunnable, 200);
        } else if(floorList.getVisibility() == View.VISIBLE){
            floorList.setVisibility(View.GONE);
        }
    }

    private Call mCallFloors = null;
    private String curParkingId = "";
    private ArrayList<ParkingFloor> parkingFloorsList = new ArrayList<>();
    private Runnable mapMoveRunnable = new Runnable() {
        @Override
        public void run() {
            if (mCallFloors != null && mCallFloors.isExecuted()) {
                mCallFloors.cancel();
            }
            LatLng TL = mMapManager.getMapBox().getProjection().fromScreenLocation(new PointF(-200, -200));
            LatLng BR = mMapManager.getMapBox().getProjection().fromScreenLocation(new PointF(mScreenWidth + 200, mScreenHeight + 200));
            mCallFloors = NetManager.getInstance().getData(UrlManager.getParkingFloors(TL.getLongitude(), TL.getLatitude(), BR.getLongitude(), BR.getLatitude()), new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    mCallFloors = null;
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    mCallFloors = null;
                    ArrayList<ParkingFloor> list = GsonManager.getInstance().parseParkingFloors(response.body().string());
                    if (list != null && list.size() > 0) {
                        ArrayList<ParkingFloor> newList = new ArrayList<>();
                        for (ParkingFloor parkingFloor1 : list) {
                            boolean his = false;
                            for (ParkingFloor parkingFloor2 : parkingFloorsList) {
                                if (parkingFloor2.getParkingId().equals(parkingFloor1.getParkingId())) {
                                    parkingFloor1.setSelectFloor(parkingFloor2.getSelectFloor());
                                    his = true;
                                    break;
                                }
                            }
                            if (!his) {
                                newList.add(parkingFloor1);
                            }
                        }

                        for (int i = 0; i < parkingFloorsList.size(); i++) {
                            ParkingFloor parkingFloor1 = parkingFloorsList.get(i);
                            boolean his = false;
                            for (ParkingFloor parkingFloor2 : list) {
                                if (parkingFloor1.getParkingId().equals(parkingFloor2.getParkingId())) {
                                    his = true;
                                    break;
                                }
                            }
                            if (!his) {
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        mMapManager.getMapStyle().removeLayer(parkingFloor1.getParkingId() + "background");
                                        mMapManager.getMapStyle().removeLayer(parkingFloor1.getParkingId() + "poi");
                                        mMapManager.getMapStyle().removeLayer(parkingFloor1.getParkingId() + "lot");
                                        mMapManager.getMapStyle().removeLayer(parkingFloor1.getParkingId() + "wall");
                                        mMapManager.getMapStyle().removeLayer(parkingFloor1.getParkingId() + "partition");
                                        mMapManager.getMapStyle().removeLayer(parkingFloor1.getParkingId() + "floors");
                                        mMapManager.getMapStyle().removeLayer(parkingFloor1.getParkingId() + "road");
                                        mMapManager.getMapStyle().removeSource(parkingFloor1.getParkingId() + "background");
                                        mMapManager.getMapStyle().removeSource(parkingFloor1.getParkingId() + "road");
                                        mMapManager.getMapStyle().removeSource(parkingFloor1.getParkingId() + "poi");
                                    }
                                });
                                parkingFloorsList.remove(i);
                                i--;
                            }
                        }


                        for (int i = 0; i < newList.size(); i++) {
                            ParkingFloor parkingFloor1 = newList.get(i);
                            NetManager.getInstance().getData(UrlManager.getParkingVectorUrl(parkingFloor1.getParkingId(), parkingFloor1.getSelectFloor()), new Callback() {
                                @Override
                                public void onFailure(Call call, IOException e) {

                                }

                                @Override
                                public void onResponse(Call call, Response response) throws IOException {
                                    try {
                                        parkingFloorsList.add(parkingFloor1);
                                        JSONObject jsonObject = new JSONObject(response.body().string());
                                        String road = jsonObject.getString("p_road");
                                        String background = jsonObject.getString("p_background");
                                        String poi = jsonObject.getString("p_poi");
                                        mHandler.post(new Runnable() {
                                            @Override
                                            public void run() {
                                                if (!TextUtils.isEmpty(background)) {
                                                    Source geoJsonSource = mMapManager.getMapStyle().getSource(parkingFloor1.getParkingId() + "background");
                                                    if (geoJsonSource == null) {
                                                        geoJsonSource = new GeoJsonSource(parkingFloor1.getParkingId() + "background", background);
                                                        mMapManager.getMapStyle().addSource(geoJsonSource);
                                                        mMapManager.getMapStyle().addLayerBelow(LayerUtil.getPBackgroundLayer(parkingFloor1.getParkingId()), routeLayerId);
                                                        mMapManager.getMapStyle().addLayerBelow(LayerUtil.getPFloorsLayer(parkingFloor1.getParkingId()), routeLayerId);
                                                        mMapManager. getMapStyle().addLayerBelow(LayerUtil.getPartitionLayer(parkingFloor1.getParkingId()), routeLayerId);
                                                        mMapManager.getMapStyle().addLayerBelow(LayerUtil.getWallLayer(parkingFloor1.getParkingId()), routeLayerId);
                                                        mMapManager.getMapStyle().addLayerBelow(LayerUtil.getLotLayer(parkingFloor1.getParkingId()), routeLayerId);
                                                    } else {
                                                        ((GeoJsonSource) geoJsonSource).setGeoJson(background);
                                                    }
                                                }
                                                if (!TextUtils.isEmpty(road)) {
                                                    Source geoJsonSource = mMapManager.getMapStyle().getSource(parkingFloor1.getParkingId() + "road");
                                                    if (geoJsonSource == null) {
                                                        geoJsonSource = new GeoJsonSource(parkingFloor1.getParkingId() + "road", road);
                                                        mMapManager.getMapStyle().addSource(geoJsonSource);
                                                        mMapManager.getMapStyle().addLayerBelow(LayerUtil.getPRoadLayer(parkingFloor1.getParkingId()), routeLayerId);
                                                    } else {
                                                        ((GeoJsonSource) geoJsonSource).setGeoJson(road);
                                                    }
                                                }
                                                if (!TextUtils.isEmpty(poi)) {
                                                    Source geoJsonSource = mMapManager.getMapStyle().getSource(parkingFloor1.getParkingId() + "poi");
                                                    if (geoJsonSource == null) {
                                                        geoJsonSource = new GeoJsonSource(parkingFloor1.getParkingId() + "poi", poi);
                                                        mMapManager.getMapStyle().addSource(geoJsonSource);
                                                        mMapManager.getMapStyle().addLayerBelow(LayerUtil.getPPoiLayer(parkingFloor1.getParkingId()), routeLayerId);
                                                    } else {
                                                        ((GeoJsonSource) geoJsonSource).setGeoJson(poi);
                                                    }
                                                }

                                            }
                                        });
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        }
                    }
                }
            });

            String parkingId = null;
            if (parkingFloorsList.size() > 0) {
                String layerId[] = new String[parkingFloorsList.size() * 7];
                for (int i = 0; i < parkingFloorsList.size(); i++) {
                    ParkingFloor floor = parkingFloorsList.get(i);
                    layerId[7 * i] = floor.getParkingId() + "background";
                    layerId[7 * i + 1] = floor.getParkingId() + "lot";
                    layerId[7 * i + 2] = floor.getParkingId() + "wall";
                    layerId[7 * i + 3] = floor.getParkingId() + "poi";
                    layerId[7 * i + 4] = floor.getParkingId() + "road";
                    layerId[7 * i + 5] = floor.getParkingId() + "partition";
                    layerId[7 * i + 6] = floor.getParkingId() + "floors";
                }
                RectF rectF = new RectF(mScreenWidth / 2 - 50, mScreenHeight / 2 - 50, mScreenWidth / 2 + 50, mScreenHeight / 2 + 50);
                List<Feature> features = mMapManager.getMapBox().queryRenderedFeatures(rectF, layerId);
                for (int i = 0; i < features.size(); i++) {
                    boolean his = false;
                    Feature feature = features.get(i);
                    if (feature.properties() != null) {
                        for (Map.Entry<String, JsonElement> entry : feature.properties().entrySet()) {
                            if (entry.getKey().equals("parking_id")) {
                                parkingId = entry.getValue().toString();
                                if (parkingId.startsWith("\"")) {
                                    parkingId = parkingId.substring(1);
                                }
                                if (parkingId.endsWith("\"")) {
                                    parkingId = parkingId.substring(0, parkingId.length() - 1);
                                }
                                his = true;
                            }
                            break;
                        }
                    }
                    if (his) {
                        break;
                    }
                }
            }
            if (parkingId == null) {
                floorList.setVisibility(View.GONE);
            } else if (parkingId != null && !parkingId.equals(curParkingId)) {
                for (ParkingFloor parkingFloor : parkingFloorsList) {
                    if (parkingFloor.getParkingId().equals(parkingId)) {
                        floorListAdapter.setData(parkingFloor.getFloors(), parkingId, parkingFloor.getSelectFloor());
                        floorList.setVisibility(View.VISIBLE);
                        break;
                    }
                }
                curParkingId = parkingId;
                return;
            } else {
                floorList.setVisibility(View.VISIBLE);
            }
        }
    };

    /**
     * 构造停车场内路径
     */
    public Map<String, Object> obtainParkingRouteMap(JSONArray parkingJsonArray, DirectionsRoute directionsRoute) throws JSONException {
        Map<String, Object> map = new HashMap<>();
        map.put(KEY_ROUTE_WHOLE, directionsRoute);
        List<DirectionsRoute> parkingRouteList = new ArrayList<>();
        if (parkingJsonArray != null) {
            for (int i = 0; i < parkingJsonArray.length(); i++) {
                JSONObject parkingJsonObj = parkingJsonArray.getJSONObject(i);
                DirectionsRoute parkRoute = DirectionsRoute.builder()
                        .geometry(parkingJsonObj.optString("geometry"))
                        .routeOptions(directionsRoute.routeOptions().toBuilder()
                                // 使用accessToken字段记录停车场路径的楼层
                                .accessToken(parkingJsonObj.optString("basementFlag", ""))
                                // 使用approaches字段记录停车场路径的停车场id
                                .approaches(parkingJsonObj.optString("parkingId", "")).build())
                        .voiceLanguage(directionsRoute.voiceLanguage())
                        .weight(directionsRoute.weight())
                        .weightName(directionsRoute.weightName())
                        .build();
                if (StringUtils.isEmpty(parkingJsonObj.optString("basementFlag", "")) && StringUtils.isEmpty(parkingJsonObj.optString("parkingId", ""))) {
                    parkRoute = parkRoute.toBuilder().legs(directionsRoute.legs()).distance(directionsRoute.distance()).duration(directionsRoute.duration()).build();
                    map.put(KEY_ROUTE_OUT, parkRoute);
                } else {
                    parkingRouteList.add(parkRoute);
                }
            }
        }
        map.put(KEY_ROUTE_PARKING, parkingRouteList);
        if (!map.containsKey(KEY_ROUTE_OUT)||map.get(KEY_ROUTE_OUT)==null){
            DirectionsRoute outRoute = DirectionsRoute.builder()
                    .geometry("")
                    .routeOptions(directionsRoute.routeOptions().toBuilder()
                            // 使用accessToken字段记录停车场路径的楼层
                            .accessToken("")
                            // 使用approaches字段记录停车场路径的停车场id
                            .approaches("").build())
                    .voiceLanguage(directionsRoute.voiceLanguage())
                    .weight(directionsRoute.weight())
                    .weightName(directionsRoute.weightName())
                    .legs(directionsRoute.legs())
                    .distance(directionsRoute.distance())
                    .duration(directionsRoute.duration())
                    .build();
            map.put(KEY_ROUTE_OUT,outRoute);
        }
        return map;
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onEventMessageMainThread(Message msg){
//        if (msg.what == 0x8888){
//            LayerUtil.drawParkingMap(new Handler(),);
//        }
//    }
}
